/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package administrator;

import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.persistence.EntityManager;
import javax.swing.JFrame;
import model.Customer;
import model.Store;
import supermarket.SuperMarket;

/**
 *
 * @author Kostas
 */
public class AdminCustProfile extends javax.swing.JFrame {

    /**
     * Creates new form AdminCustProfile
     */
    public AdminCustProfile() {
        SuperMarket sm = new SuperMarket();
        em = sm.getEm();        
        if(!(em.getTransaction().isActive()) ){
            em.getTransaction().begin();
        }
        initComponents();
    }
    
    private void closeMe(boolean exitAndSave) {
        MyWindowEvent we = new MyWindowEvent(this, WindowEvent.WINDOW_CLOSED, exitAndSave);
        for (WindowListener l : this.getWindowListeners()) {
            l.windowClosed(we);
        }
            this.setVisible(false);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        SuperMarketPUEntityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("SuperMarketPU").createEntityManager();
        customerQuery = java.beans.Beans.isDesignTime() ? null : SuperMarketPUEntityManager.createQuery("SELECT c FROM Customer c");
        customerList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(customerQuery.getResultList());
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jNewCustButton = new javax.swing.JButton();
        jEditCustButton = new javax.swing.JButton();
        jDeleteCustButton = new javax.swing.JButton();
        jCancelButton = new javax.swing.JButton();
        jSaveButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, customerList, jTable1);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${customerId}"));
        columnBinding.setColumnName("Customer Id");
        columnBinding.setColumnClass(Integer.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${pointsCardNumber}"));
        columnBinding.setColumnName("Points Card Number");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${firstName}"));
        columnBinding.setColumnName("First Name");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${lastName}"));
        columnBinding.setColumnName("Last Name");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${password}"));
        columnBinding.setColumnName("Password");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${address}"));
        columnBinding.setColumnName("Address");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${creditCardNo}"));
        columnBinding.setColumnName("Credit Card No");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${availablePoints}"));
        columnBinding.setColumnName("Available Points");
        columnBinding.setColumnClass(Integer.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${checksno}"));
        columnBinding.setColumnName("Checksno");
        columnBinding.setColumnClass(Integer.class);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();

        jScrollPane1.setViewportView(jTable1);

        jNewCustButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/add.gif"))); // NOI18N
        jNewCustButton.setText("Δημιουργία");
        jNewCustButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jNewCustButtonActionPerformed(evt);
            }
        });

        jEditCustButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/edit1.png"))); // NOI18N
        jEditCustButton.setText("Τροποποίηση");
        jEditCustButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jEditCustButtonActionPerformed(evt);
            }
        });

        jDeleteCustButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/remove.gif"))); // NOI18N
        jDeleteCustButton.setText("Διαγραφή");
        jDeleteCustButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jDeleteCustButtonActionPerformed(evt);
            }
        });

        jCancelButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/cancel.gif"))); // NOI18N
        jCancelButton.setText("Ακύρωση");
        jCancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCancelButtonActionPerformed(evt);
            }
        });

        jSaveButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/save.gif"))); // NOI18N
        jSaveButton.setText("Αποθήκευση");
        jSaveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jSaveButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jNewCustButton)
                .addGap(7, 7, 7)
                .addComponent(jEditCustButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jDeleteCustButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 204, Short.MAX_VALUE)
                .addComponent(jCancelButton)
                .addGap(18, 18, 18)
                .addComponent(jSaveButton)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 42, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jNewCustButton)
                    .addComponent(jEditCustButton)
                    .addComponent(jDeleteCustButton)
                    .addComponent(jCancelButton)
                    .addComponent(jSaveButton))
                .addGap(19, 19, 19))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        bindingGroup.bind();

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void jNewCustButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jNewCustButtonActionPerformed
       
        final Customer c = new Customer();         
        em.persist(c); 
        
        EditCustProfile ecp = new EditCustProfile(c, false, false);
        ecp.setVisible(true);
                
        thisFrame=this;
        thisFrame.setEnabled(false);
                        
        //****************
        
        ecp.addWindowListener(new WindowListener() {
            public void windowClosed(WindowEvent arg0){
                System.out.println("Window close event occur");
                 thisFrame.setEnabled(true);
               if (((MyWindowEvent)arg0).exitAndSave){
                                    
                customerList.add(c);                
                                
                System.out.println("Test point 0 ::" + "Megethos listas:" + customerList.size());
                int row = customerList.size() - 1;
                jTable1.setRowSelectionInterval(row, row);
                jTable1.scrollRectToVisible(jTable1.getCellRect(row, 0, true));
                                                                            
                System.out.println("Test point 1 ::" + " name:" + c.getFirstName()+"::"+jTable1.getRowCount());
               } 
//               else{
//                   thisFrame.setEnabled(true);
//                   em.getTransaction().rollback();
//                   em.getTransaction().begin();
//                   java.util.Collection data = storeQuery2.getResultList();
//                   for(Object entity: data){
//                       em.refresh(entity);                       
//                   }
//                   System.out.println("Test point 2");
//                   storeList2.clear();
//                   storeList2.addAll(data);
//               } 
            }
                        

            public void windowOpened(WindowEvent we) {
                    System.out.println("Window Opened");            }


            public void windowClosing(WindowEvent we) {
                    System.out.println("Window Closed");            }


            public void windowIconified(WindowEvent we) {
                    System.out.println("Window Iconified");            }


            public void windowDeiconified(WindowEvent we) {
                    System.out.println("Window Deiconified");            }


            public void windowActivated(WindowEvent we) {
                    System.out.println("Window Activated");            }


            public void windowDeactivated(WindowEvent we) {
                    System.out.println("Window Deactivated");            }
               
        });
    }//GEN-LAST:event_jNewCustButtonActionPerformed

    private void jEditCustButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jEditCustButtonActionPerformed
        
        final int c = jTable1.getSelectedRow();

        if (c >= 0) {
            final Customer c1 = customerList.get(c);
            EditCustProfile ecp = new EditCustProfile(c1, false, true);
            ecp.setVisible(true);
            thisFrame = this;
            thisFrame.setEnabled(false);
            //************
            ecp.addWindowListener(new WindowListener() {
                public void windowClosed(WindowEvent arg0) {
                    System.out.println("Window close event occur");
                    if (((MyWindowEvent)arg0).exitAndSave) {

                        em.merge(c1);

                        customerList.set(c, c1);

                    }
                    thisFrame.setEnabled(true);
                    
                }

                public void windowActivated(WindowEvent arg0) {
                    System.out.println("Window Activated");
                }

                public void windowClosing(WindowEvent arg0) {
                    System.out.println("Window Closing");
                }

                public void windowDeactivated(WindowEvent arg0) {
                    System.out.println("Window Deactivated");
                }

                public void windowDeiconified(WindowEvent arg0) {
                    System.out.println("Window Deiconified");
                }

                public void windowIconified(WindowEvent arg0) {
                    System.out.println("Window Iconified");
                }

                public void windowOpened(WindowEvent arg0) {
                    System.out.println("Window Opened");
                }
            });
        }
    }//GEN-LAST:event_jEditCustButtonActionPerformed

    private void jDeleteCustButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jDeleteCustButtonActionPerformed
         if(!(em.getTransaction().isActive()) ){
             em.getTransaction().begin();
        }
         int rownum = jTable1.getSelectedRow();
         System.out.println("Te row num is : "+rownum);
         if (rownum >= 0) {
            Customer c = customerList.get(jTable1.convertRowIndexToModel(rownum)); 
            System.out.println("Store is:: "+c.getFirstName());
            customerList.remove(c);
            em.remove(em.merge(c));
         }
    }//GEN-LAST:event_jDeleteCustButtonActionPerformed

    private void jCancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCancelButtonActionPerformed
         em.getTransaction().rollback();
         em.getTransaction().begin();        
         closeMe(false);
    }//GEN-LAST:event_jCancelButtonActionPerformed

    private void jSaveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jSaveButtonActionPerformed
         em.getTransaction().commit();
         em.getTransaction().begin();        
         closeMe(true);
    }//GEN-LAST:event_jSaveButtonActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(AdminCustProfile.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AdminCustProfile.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AdminCustProfile.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AdminCustProfile.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new AdminCustProfile().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.persistence.EntityManager SuperMarketPUEntityManager;
    private java.util.List<model.Customer> customerList;
    private javax.persistence.Query customerQuery;
    private javax.swing.JButton jCancelButton;
    private javax.swing.JButton jDeleteCustButton;
    private javax.swing.JButton jEditCustButton;
    private javax.swing.JButton jNewCustButton;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JButton jSaveButton;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
 private EntityManager em;
    JFrame thisFrame;
}
